﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SudokuWPF.UserControls
{
    /// <summary>
    /// GraphControl.xaml 的交互逻辑
    /// </summary>
    public partial class GraphControl : ListBox
    {
        public GraphControl()
        {
            InitializeComponent();
        }

        //向依赖属性注册附加属性BarHeightProperty，栏目高度属性
        public static readonly DependencyProperty BarHeightProperty = DependencyProperty.RegisterAttached("BarHeight", typeof(double), typeof(DependencyObject), new PropertyMetadata(0.0));
        //IndexProperty用于文本
        public static readonly DependencyProperty IndexProperty = DependencyProperty.RegisterAttached("Index", typeof(Int32), typeof(DependencyObject), new PropertyMetadata(0));

        //静态引用方法
        public static double GetBarHeight(DependencyObject d)
        {
            return (double)d.GetValue(BarHeightProperty);
        }
        public static void SetBarHeight(DependencyObject d, double h)
        {
            d.SetValue(BarHeightProperty, h);
        }
        
        public static Int32 GetIndex(DependencyObject d)
        {
            return (Int32)d.GetValue(IndexProperty);
        }
        public static void SetIndex(DependencyObject d, Int32 i)
        {
            d.SetValue(IndexProperty, i);
        }

        protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            base.OnItemsChanged(e);

            long maxVal = 0;
            foreach (SolverResult s in Items)
            {
                if (!s.Failed && s.TimeTaken.Ticks > maxVal) maxVal = s.TimeTaken.Ticks;
            }
            foreach (SolverResult s in Items)
            {
                if (s.Failed)
                {
                    GraphControl.SetBarHeight(s, ActualHeight - 25);
                }
                else
                {
                    double h = (double)s.TimeTaken.Ticks / (double)maxVal * (ActualHeight - 25);
                    if (h > 10)
                    {
                        GraphControl.SetBarHeight(s, h);
                    }
                    else
                    {
                        GraphControl.SetBarHeight(s, 10);
                    }
                }
                GraphControl.SetIndex(s, Items.IndexOf(s));
            }
        }
    }
}
